package com.whiteape.book.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.common.WaConstants;
import com.whiteape.book.contract.BookReadContract;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.core.page.PageLoader;
import com.whiteape.book.core.page.PageStyle;
import com.whiteape.book.core.page.PageView;
import com.whiteape.book.core.page.TxtChapter;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.DownloadTaskBean;
import com.whiteape.book.model.dto.MediaChapterBean;
import com.whiteape.book.model.dto.MediaRecordBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.type.CatalogOrderType;
import com.whiteape.book.model.type.LoadFileType;
import com.whiteape.book.model.type.SourceFromType;
import com.whiteape.book.presenter.BookReadPresenter;
import com.whiteape.book.service.VoiceService;
import com.whiteape.book.ui.adapter.BookCatalogAdapter;
import com.whiteape.book.ui.base.BaseMVPActivity;
import com.whiteape.book.ui.dialog.BookReadSettingDialogFragment;
import com.whiteape.book.utils.BitIntentDataManager;
import com.whiteape.book.utils.BrightnessUtils;
import com.whiteape.book.utils.DaoDbHelper;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.MD5Utils;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.ScreenUtils;
import com.whiteape.book.utils.SimilarityUtil;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.SystemBarUtils;
import com.whiteape.book.utils.ToastUtils;
import com.whiteape.book.utils.URLUtils;
import com.zhihu.matisse.Matisse;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

import static android.view.View.GONE;
import static android.view.View.LAYER_TYPE_SOFTWARE;
import static android.view.View.VISIBLE;

/**
 * Created by newbiechen on 17-5-16.
 */

public class BookReadActivity extends BaseMVPActivity<BookReadContract.Presenter>
        implements BookReadContract.View {
    private static final String TAG = "BookReadActivity";
    public static final int REQUEST_MORE_SETTING = 1111;
    public static final int REQUEST_CODE_CHOOSE_PICTURE = 1122;
    public static final int REQUEST_CHANGE_TYPEFACE = LoadFileType.FILE_TYPE_TYPEFACE;
    public static final int REQUEST_CHANGE_SOURCE = 2222;
    public static final int REQUEST_CODE_REPLACE_RULE = 4444;
    public static final String EXTRA_SHELF_BOOK = "extra_shelf_book";
    public static final String EXTRA_IS_IN_SHELF = "extra_is_in_shelf";
    public static final String EXTRA_CHAPTER_LIST = "extra_chapter_list";
    public static final String EXTRA_JUMP_TO_CHAPTER_INDEX = "extra_jump_to_chapter_index";
    public static final String EXTRA_JUMP_TO_CHAPTER_TITLE = "extra_jump_to_chapter_title";
    public static final String EXTRA_JUMP_TO_CHAPTER_PAGE = "extra_jump_to_chapter_page";
    public static final String EXTRA_BIG_DATA_KEY = "extra_big_data_key";

    // 注册 Brightness 的 uri
    private final Uri BRIGHTNESS_MODE_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE);
    private final Uri BRIGHTNESS_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
    private final Uri BRIGHTNESS_ADJ_URI =
            Settings.System.getUriFor("screen_auto_brightness_adj");

    private static final int WHAT_CATEGORY = 1;
    private static final int WHAT_CHAPTER = 2;
    private static final int WHAT_AUTO_READ_PROGRESS_ADD = 3;

    private static final int AUTO_SPEED_MAX = 30;
    private static final int AUTO_SPEED_MIN = 1;


    @BindView(R.id.read_dl_slide)
    DrawerLayout mDlSlide;
    @BindView(R.id.read_rl)
    RelativeLayout mReadWrapper;
    /*************top_menu_view*******************/
    @BindView(R.id.read_abl_top_menu)
    AppBarLayout mAblTopMenu;

    @BindView(R.id.read_ll_bottom_auto_read_menu)
    LinearLayout mAutoReadMenu;

    @BindView(R.id.read_ll_bottom_tts_menu)
    LinearLayout mTTSMenu;
//    @BindView(R.id.read_tv_community)
//    TextView mTvCommunity;
//    @BindView(R.id.read_tv_brief)
//    TextView mTvBrief;
    /***************content_view******************/
    @BindView(R.id.read_pv_page)
    PageView mPvPage;
    /***************bottom_menu_view***************************/
    @BindView(R.id.read_tv_page_tip)
    TextView mTvPageTip;

    @BindView(R.id.read_ll_bottom_menu)
    LinearLayout mLlBottomMenu;
    @BindView(R.id.view_placeholder)
    View viewPlaceholder;
    @BindView(R.id.read_tv_pre_chapter)
    TextView mTvPreChapter;
    @BindView(R.id.read_sb_chapter_progress)
    SeekBar mSbChapterProgress;
    @BindView(R.id.read_tv_next_chapter)
    TextView mTvNextChapter;
    @BindView(R.id.read_tv_catalog)
    TextView mTvCategory;
    @BindView(R.id.read_tv_night_mode)
    TextView mTvNightMode;
    @BindView(R.id.read_tv_download)
    TextView mTvDownload;
    @BindView(R.id.read_tv_change_source)
    TextView mTvChangeSource;
    @BindView(R.id.read_tv_setting)
    TextView mTvSetting;
    @BindView(R.id.auto_read_progress)
    ProgressBar mAutoReadProgressBar;
    @BindView(R.id.read_iv_auto_play)
    ImageView mIvAutoPlay;
    @BindView(R.id.rl_add_to_collection)
    RelativeLayout mRlAddToCollection;
    @BindView(R.id.read_iv_listen)
    ImageView mIvListen;
    @BindView(R.id.read_tv_speed_minus)
    ImageView mTvSpeedMinus;
    @BindView(R.id.read_tv_speed_add)
    ImageView mTvSpeedAdd;
    @BindView(R.id.read_tv_speed)
    TextView mTvSpeed;
    @BindView(R.id.read_tv_auto_read_exit)
    TextView mTvAutoReadExit;
    @BindView(R.id.iv_tts_stop)
    ImageView mIvTTSStop;
    @BindView(R.id.iv_tts_play)
    ImageView mIvTTSPlay;
    @BindView((R.id.iv_tts_timer))
    ImageView mIvTTSTimer;
    @BindView(R.id.tv_tts_timer)
    TextView mTvTTSTimer;
    @BindView(R.id.sb_tts_speed)
    SeekBar mSbTTSSpeed;
//    @BindView(R.id.sb_tts_volume)
//    SeekBar mSbTTSVolume;
    /***************left slide*******************************/
    @BindView(R.id.read_iv_catalog)
    ListView mLvCategory;

    @BindView(R.id.iv_catalog_order)
    ImageView ivCatalogOrder;

    @BindView(R.id.tv_catalog_order)
    TextView tvCatalogOrder;


//    @BindView(R.id.status_bar_view)
//    View mStatusBarView;
    /*****************view******************/
//    private BookReadSettingDialog mSettingDialog;
    private BookReadSettingDialogFragment mSettingDialogFragment;
    private PageLoader mPageLoader;
    private Animation mTopInAnim;
    private Animation mTopOutAnim;
    private Animation mBottomInAnim;
    private Animation mBottomOutAnim;
    private Animation mLeftOutAnim;
    private Animation mLeftInAnim;
    private Animation mRightInAnim;
    private Animation mRightOutAnim;
    private BookCatalogAdapter mBookCatalogAdapter;
    private CollectionMediaBean mCollectionMediaBean;
    private SiteSourceBean mSiteSourceBean;

    public static List<MediaChapterBean> inputChapterBeanList;
    private int inputChapterIndex = -1;
    private String inputChapterTitle = null;
    private int inputPage = 0;
    private boolean autoReading = false;
    private boolean isTTSRunning = false;
    private boolean isTTSPaused = false;
    private int timerSeconds = -1;
    private boolean ttsTimerRunning = false;
    private CountDownTimer countDownTimer;
    CatalogOrderType catalogOrderType = CatalogOrderType.ORDER_ASC;
    private int autoReadSpeed = ReadSettingManager.getInstance().getAutoReadSpeed();
//    private ImmersionBar mImmersionBar;
//    private TextToSpeech mTTS;

    //控制屏幕常亮
//    private PowerManager.WakeLock mWakeLock;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case WHAT_CATEGORY:
                    mLvCategory.setSelection(mPageLoader.getChapterPos());
                    break;
                case WHAT_CHAPTER:
                    mPageLoader.openChapter();
                    break;
                case WHAT_AUTO_READ_PROGRESS_ADD:
                    if (mAutoReadProgressBar == null) {
                        return;
                    }
                    int currentProgress = mAutoReadProgressBar.getProgress();
                    mAutoReadProgressBar.setProgress(currentProgress + 1);
                    if (currentProgress >= 1000) {
                        if (mPageLoader != null && mPageLoader.getPageStatus() !=
                                mPageLoader.STATUS_LOADING &&
                                mPageLoader.getPageStatus() != PageLoader.STATUS_ERROR &&
                                mPageLoader.getPageStatus() != PageLoader.STATUS_PARING) {
                            mPageLoader.skipToNextPage();
                        }
                        mAutoReadProgressBar.setProgress(0);
                    }
                    break;
            }
        }
    };

    // 接收电池信息和时间更新的广播
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (isDestroyed() || isFinishing() || !hasWindowFocus()) {
                return;
            }
            if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
                int level = intent.getIntExtra("level", 0);
                mPageLoader.updateBattery(level);
            }
            // 监听分钟的变化
            else if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                mPageLoader.updateTime();
            }
        }
    };

    // 亮度调节监听
    // 由于亮度调节没有 Broadcast 而是直接修改 ContentProvider 的。所以需要创建一个 Observer 来监听 ContentProvider 的变化情况。
    private ContentObserver mBrightObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            onChange(selfChange, null);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange);

            // 判断当前是否跟随屏幕亮度，如果不是则返回
            boolean isBrightnessAuto = ReadSettingManager.getInstance().isBrightnessAuto();
            if (selfChange || !isBrightnessAuto) {
                return;
            }

            // 如果系统亮度改变，则修改当前 Activity 亮度
            if (BRIGHTNESS_MODE_URI.equals(uri)) {
                Log.d(TAG, "亮度模式改变");
            } else if (BRIGHTNESS_URI.equals(uri) && !BrightnessUtils.isAutoBrightness(BookReadActivity.this)) {
                Log.d(TAG, "亮度模式为手动模式 值改变");
                BrightnessUtils.setBrightness(BookReadActivity.this, BrightnessUtils.getScreenBrightness(BookReadActivity.this));
            } else if (BRIGHTNESS_ADJ_URI.equals(uri) && BrightnessUtils.isAutoBrightness(BookReadActivity.this)) {
                Log.d(TAG, "亮度模式为自动模式 值改变");
                BrightnessUtils.setDefaultBrightness(BookReadActivity.this);
            } else {
                Log.d(TAG, "亮度调整 其他");
            }
        }
    };

    /***************params*****************/
    private boolean isCollected = false; // isFromSDCard
    private boolean isNightMode = false;
    private boolean isFullScreen = false;
    private boolean isRegistered = false;


    //    public static void startActivity(Context context, CollectionMediaBean collectionMediaBean,
//                                       List<MediaChapterBean> beanList, boolean isCollected,
//                                       int chapterIndex, boolean recreate) {
//        if (recreate) {
//
//        }
//
//    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public static void startActivity(Context context, CollectionMediaBean collectionMediaBean,
                                     boolean isCollected,
                                     int chapterIndex) {
        startActivity(context, collectionMediaBean, null, isCollected, chapterIndex, null, 0);
    }

    public static void startActivity(Context context, CollectionMediaBean collectionMediaBean,
                                     List<MediaChapterBean> beanList, boolean isCollected,
                                     int chapterIndex, String chapterTitle, int page) {

        inputChapterBeanList = beanList;
        //上面这个beanList太大没法保存在intent/bundle中，需要用中转存储
        context.startActivity(new Intent(context, BookReadActivity.class)
                        .putExtra(EXTRA_IS_IN_SHELF, isCollected)
                        .putExtra(EXTRA_SHELF_BOOK, collectionMediaBean)
//                .putExtra(EXTRA_CHAPTER_LIST, (Serializable) beanList)
                        .putExtra(EXTRA_JUMP_TO_CHAPTER_INDEX, chapterIndex)
                        .putExtra(EXTRA_JUMP_TO_CHAPTER_TITLE, chapterTitle)
                        .putExtra(EXTRA_JUMP_TO_CHAPTER_PAGE, page)

        );
    }


    @Override
    protected int getContentId() {
        return R.layout.activity_book_read;
    }


    private int getBatteryNow() {
        //通过粘性广播读取电量
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent intentBattery = registerReceiver(null, intentFilter);//注意，粘性广播不需要广播接收器
        if (intentBattery != null) {
            //获取当前电量
            int batteryLevel = intentBattery.getIntExtra("level", 0);
//            //电量的总刻度
//            int batterySum = intentBattery.getIntExtra("scale", 100);
//            return 100 * (float) batteryLevel / (float) batterySum;
            return batteryLevel;
        }
        return 0;

    }

    @Override
    protected BookReadContract.Presenter bindPresenter() {
        return new BookReadPresenter();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        initDataLocal(savedInstanceState);
    }

    private void initDataLocal(Bundle bundle) {
//        mTTS = new TextToSpeech(this, new TTSListener());

//        ReadSettingManager.getInstance().setAutoBrightness(true);

        //TODO 进来先保存进度，没有加入书架的书籍会不会有问题呢？
        String bigDataKey = getIntent().getStringExtra(EXTRA_BIG_DATA_KEY);
        if (bigDataKey != null) {
            inputChapterBeanList = (List<MediaChapterBean>) BitIntentDataManager.getInstance().getData(bigDataKey);
        }
        if (bundle != null) {
            mCollectionMediaBean = bundle.getParcelable(EXTRA_SHELF_BOOK);
            isCollected = bundle.getBoolean(EXTRA_IS_IN_SHELF, false);
            inputChapterIndex = bundle.getInt(EXTRA_JUMP_TO_CHAPTER_INDEX, 0);
            inputChapterTitle = bundle.getString(EXTRA_JUMP_TO_CHAPTER_TITLE);
            inputPage = bundle.getInt(EXTRA_JUMP_TO_CHAPTER_PAGE, 0);

        } else {
            mCollectionMediaBean = getIntent().getParcelableExtra(EXTRA_SHELF_BOOK);
            isCollected = getIntent().getBooleanExtra(EXTRA_IS_IN_SHELF, false);
            inputChapterIndex = getIntent().getIntExtra(EXTRA_JUMP_TO_CHAPTER_INDEX, 0);
            inputChapterTitle = getIntent().getStringExtra(EXTRA_JUMP_TO_CHAPTER_TITLE);
            inputPage = getIntent().getIntExtra(EXTRA_JUMP_TO_CHAPTER_PAGE, 0);

        }

        isNightMode = ReadSettingManager.getInstance().isNightMode();
        isFullScreen = ReadSettingManager.getInstance().isFullScreen();

        mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        mSiteSourceBean = mCollectionMediaBean.getSiteSourceBean();

    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(EXTRA_SHELF_BOOK, mCollectionMediaBean);
        outState.putBoolean(EXTRA_IS_IN_SHELF, isCollected);
        outState.putInt(EXTRA_JUMP_TO_CHAPTER_INDEX, inputChapterIndex);
        outState.putInt(EXTRA_JUMP_TO_CHAPTER_PAGE, inputPage);
        outState.putString(EXTRA_JUMP_TO_CHAPTER_TITLE, inputChapterTitle);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mCollectionMediaBean = savedInstanceState.getParcelable(EXTRA_SHELF_BOOK);
        isCollected = savedInstanceState.getBoolean(EXTRA_IS_IN_SHELF);
        inputChapterIndex = savedInstanceState.getInt(EXTRA_JUMP_TO_CHAPTER_INDEX);
        inputPage = savedInstanceState.getInt(EXTRA_JUMP_TO_CHAPTER_PAGE);
        inputChapterTitle = savedInstanceState.getString(EXTRA_JUMP_TO_CHAPTER_TITLE);
    }

    @Override
    public void recreate() {
        String bigDataKey = "activity_" + System.nanoTime();
        BitIntentDataManager.getInstance().putData(bigDataKey, inputChapterBeanList);
        getIntent().putExtra(EXTRA_BIG_DATA_KEY, bigDataKey);
        super.recreate();
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
        //设置标题
//        toolbar.setTitle(mCollectionMediaBean.getTitle());
        if (null != getSupportActionBar()) {
            getSupportActionBar().setTitle(mCollectionMediaBean.getTitle());
        }
        toolbar.setNavigationOnClickListener(v -> {
            if (!mCollectionMediaBean.getIfLocal() && !isCollected
                    && !mCollectionMediaBean.getMediaChapterList().isEmpty()) {
                showDialogAndExit();
            } else {
                exit();
            }
        });
        //半透明化StatusBar
//        SystemBarUtils.transparentStatusBar(this);
    }

    @Override
    protected void initView() {
        super.initView();

        // 如果 API < 18 取消硬件加速
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mPvPage.setLayerType(LAYER_TYPE_SOFTWARE, null);
        }

        //获取页面加载器
        mPageLoader = mPvPage.getPageLoader(mCollectionMediaBean);

        //禁止滑动展示DrawerLayout
        mDlSlide.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        //侧边打开后，返回键能够起作用
        mDlSlide.setFocusableInTouchMode(false);
//        mSettingDialog = new BookReadSettingDialog(this, mPageLoader);
        mSettingDialogFragment = new BookReadSettingDialogFragment();
        mSbTTSSpeed.setProgress((int) (ReadSettingManager.getInstance().getTTSSpeed() * 10));

        setUpAdapter();

//        initNavigationBar();

        //夜间模式按钮的状态
        toggleNightMode();

        initMenuAnim();

        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(mReceiver, intentFilter);

        //设置当前Activity的Brightness
        if (ReadSettingManager.getInstance().isBrightnessAuto()) {
            BrightnessUtils.setDefaultBrightness(this);
        } else {
            BrightnessUtils.setBrightness(this, ReadSettingManager.getInstance().getBrightness());
        }

        //初始化屏幕常亮类
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, ":keep bright");

        //隐藏StatusBar
//        mPvPage.post(this::hideSystemBar);

        //初始化TopMenu
        initTopMenu();

        //初始化BottomMenu
        initBottomMenu();

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        initBar();
//        SystemBarUtils.transparentStatusBar(this);
//        mImmersionBar = ImmersionBar.with(this);
//        ImmersionBar.hideStatusBar(getWindow());
        //
//        mStatusBarView.setBackgroundColor(getResources().getColor(R.color.read_bg_1));
//                .statusBarColor(ReadSettingManager.getInstance().getPageStyle().getBgColor())
//                .navigationBarColor(R.color.read_bg_1)
//                .statusBarColor(R.color.read_bg_1)
//                .navigationBarColor(R.color.read_bg_1)

//        mReadWrapper.setBackgroundColor(ReadSettingManager.getInstance().getPageStyle().getBgColor());
//        mReadWrapper.setPadding(0,ImmersionBar.getStatusBarHeight(this),0,0);
//        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(mReadWrapper.getLayoutParams());
//        lp.setMargins(lp.leftMargin, ImmersionBar.getStatusBarHeight(this), lp.rightMargin, lp.bottomMargin);
//        mReadWrapper.setLayoutParams(lp);

    }

    public void initBar() {

        boolean hideStatusBar = ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_HIDE_STATUS_BAR);
        boolean hideNavBar = ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_HIDE_NAV_BAR);
        if (hideStatusBar && hideNavBar) {
            mImmersionBar.hideBar(BarHide.FLAG_HIDE_BAR);
        } else if (hideStatusBar) {
            mImmersionBar.hideBar(BarHide.FLAG_HIDE_STATUS_BAR);
        } else if (hideNavBar) {
            mImmersionBar.hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR);
        } else {
            mImmersionBar.hideBar(BarHide.FLAG_SHOW_BAR);
        }
        mImmersionBar.init();
        if (ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_KEEP_SCREEN_ON)) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
//        if(hideStatusBar){
//            SystemBarUtils.hideStableStatusBar(this);
//        }else{
//            SystemBarUtils.showStableStatusBar(this);
//        }
//        if(hideNavBar){
//            ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_BAR).init();
////            SystemBarUtils.hideStableNavBar(this);
//        }else{
//            ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
//        }
    }

    private void initTopMenu() {
        if (Build.VERSION.SDK_INT >= 19) {
            mAblTopMenu.setPadding(0, ScreenUtils.getStatusBarHeight(), 0, 0);
        }
    }

    public PageLoader getPageLoader() {
        return mPageLoader;
    }
//    public void barChanged() {
//        boolean hideStatusBar = ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_HIDE_STATUS_BAR);
//        boolean hideNavBar = ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_HIDE_STATUS_BAR);
//        if(hideStatusBar && hideNavBar){
//            SystemBarUtils.setSystemUIVisible(this, false);
//        }
//        if(!hideStatusBar && !hideNavBar){
//            SystemBarUtils.setSystemUIVisible(this, true);
//        }
//        if(hideStatusBar && !hideNavBar){
//            SystemBarUtils.setStatusBarVisibility(this, false);
//            SystemBarUtils.setNavigationBarVisibility(this,true);
//        }
//        if(!hideStatusBar && hideNavBar){
//            SystemBarUtils.setStatusBarVisibility(this, true);
//            SystemBarUtils.setNavigationBarVisibility(this,false);
//        }
//        initBottomMenu();
//    }

    private void initBottomMenu() {
        //判断是否全屏
//        if (ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_HIDE_NAV_BAR)) {
//            //还需要设置mBottomMenu的底部高度
//            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mLlBottomMenu.getLayoutParams();
//            params.bottomMargin = ScreenUtils.getNavigationBarHeight();
//            mLlBottomMenu.setLayoutParams(params);
//        } else {
//            //设置mBottomMenu的底部距离
//            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mLlBottomMenu.getLayoutParams();
//            params.bottomMargin = 0;
//            mLlBottomMenu.setLayoutParams(params);
//        }

//        if (ImmersionBar.hasNavigationBar(this)) {
//            viewPlaceholder.getLayoutParams().height = ImmersionBar.getNavigationBarHeight(this);
//        }
        updateAutoReadSpeed();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        initImmersionBar();
        Log.d(TAG, "onWindowFocusChanged: " + mAblTopMenu.getMeasuredHeight());
    }

    private void toggleNightMode() {
        if (isNightMode) {
            mTvNightMode.setText(StringUtils.getString(R.string.wa_mode_morning));
            Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.ic_read_menu_morning);
            mTvNightMode.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        } else {
            mTvNightMode.setText(StringUtils.getString(R.string.wa_mode_night));
            Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.ic_read_menu_night);
            mTvNightMode.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        }
    }

    private void setUpAdapter() {
        mBookCatalogAdapter = new BookCatalogAdapter();
        mLvCategory.setAdapter(mBookCatalogAdapter);
        mLvCategory.setFastScrollEnabled(true);
    }

    // 注册亮度观察者
    private void registerBrightObserver() {
        try {
            if (mBrightObserver != null) {
                if (!isRegistered) {
                    final ContentResolver cr = getContentResolver();
                    cr.unregisterContentObserver(mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_MODE_URI, false, mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_URI, false, mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_ADJ_URI, false, mBrightObserver);
                    isRegistered = true;
                }
            }
        } catch (Throwable throwable) {
            LogUtils.e(TAG, "register mBrightObserver error! " + throwable);
        }
    }

    //解注册
    private void unregisterBrightObserver() {
        try {
            if (mBrightObserver != null) {
                if (isRegistered) {
                    getContentResolver().unregisterContentObserver(mBrightObserver);
                    isRegistered = false;
                }
            }
        } catch (Throwable throwable) {
            LogUtils.e(TAG, "unregister BrightnessObserver error! " + throwable);
        }
    }

    private void initPageLoaderEvent() {
//        mPageLoader.setTTSDataListener(this);

        mPageLoader.setOnPageChangeListener(
                new PageLoader.OnPageChangeListener() {

                    @Override
                    public void onChapterChange(int pos) {
                        if (catalogOrderType == CatalogOrderType.ORDER_ASC) {
                            mBookCatalogAdapter.setChapter(pos);
                        } else {
                            mBookCatalogAdapter.setChapter(mBookCatalogAdapter.getCount() - pos);
                        }
                    }

                    @Override
                    public void requestChapters(List<TxtChapter> requestChapters) {
                        mPresenter.loadChapter(mSiteSourceBean, mCollectionMediaBean, mCollectionMediaBean.getId(), requestChapters);
                        mHandler.sendEmptyMessage(WHAT_CATEGORY);
                        //隐藏提示
                        mTvPageTip.setVisibility(GONE);
                    }

                    @Override
                    public void onCategoryFinish(List<TxtChapter> chapters) {
                        for (TxtChapter chapter : chapters) {
                            chapter.setTitle(StringUtils.convertCC(chapter.getTitle(), mPvPage.getContext()));
                        }
                        if (catalogOrderType == CatalogOrderType.ORDER_DESC) {
                            Collections.reverse(chapters);
                        }
                        mBookCatalogAdapter.refreshItems(chapters);
                    }

                    @Override
                    public void onPageCountChange(int count) {
                        mSbChapterProgress.setMax(Math.max(0, count - 1));
                        mSbChapterProgress.setProgress(0);
                        // 如果处于错误状态，那么就冻结使用
                        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING
                                || mPageLoader.getPageStatus() == PageLoader.STATUS_ERROR) {
                            mSbChapterProgress.setEnabled(false);
                        } else {
                            mSbChapterProgress.setEnabled(true);
                        }
                    }

                    @Override
                    public void onPageChange(int pos) {
                        mSbChapterProgress.post(
                                () -> {
                                    if (mSbChapterProgress != null) {
                                        mSbChapterProgress.setProgress(pos);
                                    }
                                }
                        );
                    }
                }
        );
    }

    private void catalogOrderChanged() {


        if (catalogOrderType == CatalogOrderType.ORDER_ASC) {
            ivCatalogOrder.setBackgroundResource(R.mipmap.ic_read_catalog_order_desc);
            catalogOrderType = CatalogOrderType.ORDER_DESC;
            tvCatalogOrder.setText(R.string.wa_read_catalog_order_desc);
        } else {
            ivCatalogOrder.setBackgroundResource(R.mipmap.ic_read_catalog_order_asc);
            catalogOrderType = CatalogOrderType.ORDER_ASC;
            tvCatalogOrder.setText(R.string.wa_read_catalog_order_asc);
        }
        mBookCatalogAdapter.reverseItems();
        mBookCatalogAdapter.notifyDataSetChanged();
        mLvCategory.setSelection(mBookCatalogAdapter.getCount() - mLvCategory.getSelectedItemPosition());

    }

    @Override
    protected void initEvent() {
        super.initEvent();

        initPageLoaderEvent();

//        mSettingDialogFragment.getReadSettingCommonFragment().setListener(pageStyle -> {
//            initImmersionBar();
//        });

        mSbChapterProgress.setOnSeekBarChangeListener(
                new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if (mLlBottomMenu.getVisibility() == VISIBLE) {
                            //显示标题
                            mTvPageTip.setText((progress + 1) + "/" + (mSbChapterProgress.getMax() + 1));
                            mTvPageTip.setVisibility(VISIBLE);
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        //进行切换
                        int pagePos = mSbChapterProgress.getProgress();
                        if (pagePos != mPageLoader.getPagePos()) {
                            mPageLoader.skipToPage(pagePos);
                        }
                        //隐藏提示
                        mTvPageTip.setVisibility(GONE);
                    }
                }
        );

        mPvPage.setTouchListener(new PageView.TouchListener() {
            @Override
            public boolean onTouch() {
                return !hideReadMenu();
            }

            @Override
            public void center() {
                toggleMenu(true);
            }

            @Override
            public void prePage() {
                if (mPageLoader != null && isCollected) {
                    mPageLoader.saveRecord();
                }
            }

            @Override
            public void nextPage() {
                if (mPageLoader != null && isCollected) {
                    mPageLoader.saveRecord();
                }
            }

            @Override
            public void cancel() {
            }
        });

        ivCatalogOrder.setOnClickListener(v -> catalogOrderChanged());
        tvCatalogOrder.setOnClickListener(v -> catalogOrderChanged());
        mLvCategory.setOnItemClickListener(
                (parent, view, position, id) -> {
                    mDlSlide.closeDrawer(GravityCompat.START);
                    mPageLoader.skipToChapter(position);
                }
        );

        mTvCategory.setOnClickListener(
                (v) -> {
                    //移动到指定位置
                    if (mBookCatalogAdapter.getCount() > 0) {
                        if (catalogOrderType == CatalogOrderType.ORDER_ASC) {
                            mLvCategory.setSelection(mPageLoader.getChapterPos());
                        } else {
                            mLvCategory.setSelection(mBookCatalogAdapter.getCount() - mPageLoader.getChapterPos());
                        }
                    }
                    //切换菜单
                    toggleMenu(true);
                    //打开侧滑动栏
                    mDlSlide.openDrawer(GravityCompat.START);
                }
        );
        mTvChangeSource.setOnClickListener(
                (v -> {

                    //TODO 先保存记录，方便换源的时候找到对应的章节定位
                    // 会多出没有收藏的章节信息，需要定时清理？
                    toggleMenu(false);
                    mPageLoader.saveRecord();
                    mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
                    //可能遇到还没加载好，就点击换源的，这里还没章节
                    String currentChapterName = "";
                    List<MediaChapterBean> chapterBeanList = mCollectionMediaBean.getMediaChapterList();
                    if (chapterBeanList != null && chapterBeanList.size() > 0) {
                        chapterBeanList.get(mPageLoader.getChapterPos()).getName();
                    }
                    ChangeSourceActivity.startActivityForResult(REQUEST_CHANGE_SOURCE, this, mCollectionMediaBean/*, currentChapterName, mPageLoader.getPagePos(), isCollected*/);
                })
        );
        mTvSetting.setOnClickListener(
                (v) -> {
//                    mSettingDialog.show();
                    if (mSettingDialogFragment != null &&
                            !mSettingDialogFragment.isVisible() &&
                            !mSettingDialogFragment.isAdded() &&
                            !mSettingDialogFragment.isRemoving()) {
                        mSettingDialogFragment.show(getSupportFragmentManager(), "xx");
                    }
                    toggleMenu(false);
                }
        );

        mTvPreChapter.setOnClickListener(
                (v) -> {
                    if (mPageLoader.skipPreChapter()) {
                        if (catalogOrderType == CatalogOrderType.ORDER_ASC) {
                            mBookCatalogAdapter.setChapter(mPageLoader.getChapterPos());
                        } else {
                            mBookCatalogAdapter.setChapter(mBookCatalogAdapter.getCount() - mPageLoader.getChapterPos());
                        }
                    }
                }
        );

        mTvNextChapter.setOnClickListener(
                (v) -> {
                    if (mPageLoader.skipNextChapter()) {

                        if (catalogOrderType == CatalogOrderType.ORDER_ASC) {
                            mBookCatalogAdapter.setChapter(mPageLoader.getChapterPos());
                        } else {

                            mBookCatalogAdapter.setChapter(mBookCatalogAdapter.getCount() - mPageLoader.getChapterPos());
                        }
                    }
                }
        );

        mTvNightMode.setOnClickListener(
                (v) -> {
                    if (isNightMode) {
                        isNightMode = false;
                    } else {
                        isNightMode = true;
                    }
                    mPageLoader.setNightMode(isNightMode);
                    toggleNightMode();
                }
        );
        mTvDownload.setOnClickListener(
                (view -> {
                    //startActivityForResult(new Intent(BookReadActivity.this, ReplaceRuleActivity.class), REQUEST_CODE_REPLACE_RULE);
                    saveMedia();
                    showDownloadDialog();
                })
        );

        //TODO
//        mTvBrief.setOnClickListener(
//                (v) -> MediaDetailActivity.startActivity(this, mCollectionMediaBean, inputChapterBeanList)
//        );
//
//        mTvCommunity.setOnClickListener(
//                (v) -> {
//                    Intent intent = new Intent(this, CommunityActivity.class);
//                    startActivity(intent);
//                }
//        );

//        mSettingDialog.setOnDismissListener(
//                dialog -> hideSystemBar()
//        );

        mIvAutoPlay.setOnClickListener(v -> {
            hideReadMenu();
            autoReading = true;
            mAutoReadProgressBar.setVisibility(VISIBLE);
            mAutoReadProgressBar.setMax(1000);
            mAutoReadProgressBar.setProgress(0);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (autoReading) {
                        mHandler.sendEmptyMessage(WHAT_AUTO_READ_PROGRESS_ADD);
                        mHandler.postDelayed(this, 100 / autoReadSpeed);
                    }
                }
            }, 100 / autoReadSpeed);
        });
        mRlAddToCollection.setOnClickListener( view -> {
            mRlAddToCollection.setVisibility(GONE);
            mRlAddToCollection.startAnimation(mRightOutAnim);
            saveMedia();
        });

        mTvSpeedMinus.setOnClickListener(v -> {
            if (autoReadSpeed <= AUTO_SPEED_MIN) {
                return;
            }
            autoReadSpeed -= 1;
            updateAutoReadSpeed();
        });

        mTvSpeedAdd.setOnClickListener(v -> {
            if (autoReadSpeed >= AUTO_SPEED_MAX) {
                return;
            }
            autoReadSpeed += 1;
            updateAutoReadSpeed();
        });

        mTvAutoReadExit.setOnClickListener(v -> {
            autoReading = false;
            mAutoReadProgressBar.setVisibility(GONE);
            mAutoReadMenu.setVisibility(GONE);
        });

        // 以下是TTS相关
        mIvListen.setOnClickListener(v -> {
            hideReadMenu();
            isTTSRunning = true;
            isTTSPaused = false;
            mPageLoader.startTTS();
        });
        mSbTTSSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                if (progress == 0) {
                    progress = 1;
                }
                float speed = progress / 10.0f;
                ReadSettingManager.getInstance().setTTSSpeed(speed);
                VoiceService.changeSpeed(BookReadActivity.this, speed);
                ToastUtils.show("下段文字开始生效");

            }
        });
        mIvTTSPlay.setOnClickListener(v -> {
            if (!isTTSPaused) {
                mIvTTSPlay.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);
                VoiceService.pause(this);
            } else {
                mIvTTSPlay.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
                VoiceService.resume(this);
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                if (ttsTimerRunning) {
                    countDownTimer = new CountDownTimer(timerSeconds * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            if (!ttsTimerRunning || isTTSPaused) {
                                return;
                            }
                            timerSeconds -= 1;
                            mTvTTSTimer.setText(StringUtils.formatTime(timerSeconds));

                        }

                        @Override
                        public void onFinish() {
                            stopTTS();

                        }
                    };
                    countDownTimer.start();
                }
            }
            isTTSPaused = !isTTSPaused;
//            isTTSRunning = !isTTSRunning;
        });
        mIvTTSTimer.setOnClickListener(v -> {
            String[] timerChoice = new String[]{"30分钟", "60分钟", "90分钟", "120分钟", "永久"};
            new AlertDialog.Builder(this)
                    .setTitle(R.string.wa_common_timer_tip)
                    .setItems(timerChoice, ((dialogInterface, i) -> {
                        switch (i) {
                            case 0:
                                ttsTimerRunning = true;
                                timerSeconds = 30 * 60;
                                break;
                            case 1:
                                ttsTimerRunning = true;
                                timerSeconds = 60 * 60;
                                break;
                            case 2:
                                ttsTimerRunning = true;
                                timerSeconds = 90 * 60;
                                break;
                            case 3:
                                ttsTimerRunning = true;
                                timerSeconds = 120 * 60;
                                break;
                            case 4:
                                ttsTimerRunning = false;
                                timerSeconds = -1;
                                break;
                        }
                        if (ttsTimerRunning) {
                            mTvTTSTimer.setVisibility(VISIBLE);
                            mTvTTSTimer.setText(StringUtils.formatTime(timerSeconds));
                            if (countDownTimer != null) {
                                countDownTimer.cancel();
                            }
                            countDownTimer = new CountDownTimer(timerSeconds * 1000, 1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                    if (!ttsTimerRunning || isTTSPaused) {
                                        return;
                                    }
                                    timerSeconds -= 1;
                                    mTvTTSTimer.setText(StringUtils.formatTime(timerSeconds));

                                }

                                @Override
                                public void onFinish() {
                                    stopTTS();

                                }
                            };
                            countDownTimer.start();
                        } else {

                            mTvTTSTimer.setVisibility(View.INVISIBLE);
                        }

                    }))
                    .show();

        });
        mIvTTSStop.setOnClickListener(v -> {
            stopTTS();
        });


    }

    private void stopTTS() {
        if (!isTTSRunning) {
            return;
        }
        isTTSRunning = false;
        VoiceService.stop(this);
        mIvTTSPlay.setImageResource(R.drawable.ic_pause_24dp);
        if (mPageLoader != null) {
            mPageLoader.stopTTS();
        }
        mTvTTSTimer.setVisibility(View.INVISIBLE);
        mTTSMenu.setVisibility(GONE);
    }

    private void updateAutoReadSpeed() {
        ReadSettingManager.getInstance().setAutoReadSpeed(autoReadSpeed);
        mTvSpeed.setText(autoReadSpeed + "");
    }

    private void showDownloadDialog() {
        String[] chapterChoice = new String[]{"后面50章", "后面全部章节", "全部章节", "算了不下了"};
        new AlertDialog.Builder(this)
                .setTitle(R.string.wa_common_download_tip)
                .setItems(chapterChoice, ((dialogInterface, i) -> {
                    List<MediaChapterBean> chapterBeanList = new ArrayList<>();
                    mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
                    List<MediaChapterBean> chapterAll = mCollectionMediaBean.getMediaChapterList();
                    switch (i) {
                        case 0:
                            chapterBeanList.addAll(chapterAll.subList(mPageLoader.getChapterPos(),
                                    mPageLoader.getChapterPos() + 51 > chapterAll.size() ? chapterAll.size() : mPageLoader.getChapterPos() + 51));
                            break;
                        case 1:
                            chapterBeanList.addAll(chapterAll.subList(mPageLoader.getChapterPos(), chapterAll.size()));
                            MediaChapterBean mediaChapterBean = new MediaChapterBean();
                            mediaChapterBean.setLink(null);
                            chapterBeanList.add(mediaChapterBean);
                            break;
                        case 2:
                            chapterBeanList.addAll(chapterAll);
                            MediaChapterBean mediaChapterBean2 = new MediaChapterBean();
                            mediaChapterBean2.setLink(null);
                            chapterBeanList.add(mediaChapterBean2);
                            break;
                        case 3:
                            break;
                    }

                    DownloadTaskBean downloadTaskBean = new DownloadTaskBean();
                    downloadTaskBean.setTaskName(mCollectionMediaBean.getId());
                    downloadTaskBean.setCollectionMediaBean(mCollectionMediaBean);
                    downloadTaskBean.setMediaId(mCollectionMediaBean.getId());
                    downloadTaskBean.setBookChapters(chapterBeanList);
//                    downloadTaskBean.setLastChapter();

                    //先保存，才会保存章节，而且下载的，都需要先收藏 ,必须在setBookChapters后面，因为里面会给chapter设定task_name
                    MediaStorageManager.getInstance().updateCollectionMediaWithReplace(mCollectionMediaBean);

                    MediaStorageManager.getInstance().saveDownloadTask(downloadTaskBean);
                    RxBus.get().post(RxEvent.DOWNLOAD_TASK_ADD, downloadTaskBean);
                    startActivity(new Intent(this, DownloadActivity.class));


                })).show();
    }

    private void initNavigationBar() {
        PageStyle pageStyle = ReadSettingManager.getInstance().getPageStyle();

        SystemBarUtils.setNavigationBarColor(this, getResources().getColor(R.color.black));
    }

    /**
     * 隐藏阅读界面的菜单显示
     *
     * @return 是否隐藏成功
     */
    private boolean hideReadMenu() {
        hideSystemBar();
        if (mAblTopMenu.getVisibility() == VISIBLE) {
            toggleMenu(true);
            return true;
        }
//        else if (mSettingDialog.isShowing()) {
//            mSettingDialog.dismiss();
//            return true;
//        }
        else if (mSettingDialogFragment.getDialog() != null && mSettingDialogFragment.getDialog().isShowing()) {
            mSettingDialogFragment.dismiss();
            return true;

        }
        return false;
    }

    private void showSystemBar() {
        //显示
        SystemBarUtils.showUnStableStatusBar(this);
        if (isFullScreen) {
            SystemBarUtils.showUnStableNavBar(this);
        }
    }

    private void hideSystemBar() {
        initBar();
//        //隐藏
//        if (ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_HIDE_STATUS_BAR)) {
//            SystemBarUtils.hideStableStatusBar(this);
//        }
//
//        if (ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_HIDE_NAV_BAR)) {
//            SystemBarUtils.hideStableNavBar(this);
//        }
//        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
    }

    /**
     * 切换菜单栏的可视状态
     * 默认是隐藏的
     */
    private void toggleMenu(boolean hideStatusBar) {
//        initMenuAnim();
//
//        ImmersionBar.with(this).hideBar(BarHide.FLAG_SHOW_BAR).init();
//        if (hideStatusBar) {
//            hideSystemBar();
//        }
        if (autoReading || isTTSRunning) {
            mAblTopMenu.setVisibility(GONE);
            mLlBottomMenu.setVisibility(GONE);
            mTvPageTip.setVisibility(GONE);
            mIvAutoPlay.setVisibility(GONE);
            mRlAddToCollection.setVisibility(GONE);
            mIvListen.setVisibility(GONE);
            if (autoReading) {
                if (mAutoReadMenu.getVisibility() == VISIBLE) {
                    mAutoReadMenu.startAnimation(mBottomOutAnim);
                    mAutoReadMenu.setVisibility(GONE);
                } else {
                    mAutoReadMenu.startAnimation(mBottomInAnim);
                    mAutoReadMenu.setVisibility(VISIBLE);
                }
            }
            if (isTTSRunning) {
                if (mTTSMenu.getVisibility() == VISIBLE) {
                    mTTSMenu.startAnimation(mBottomOutAnim);
                    mTTSMenu.setVisibility(GONE);
                } else {
                    mTTSMenu.startAnimation(mBottomInAnim);
                    mTTSMenu.setVisibility(VISIBLE);
                }
            }
            return;
        } else {
            mAutoReadProgressBar.setVisibility(GONE);
            mAutoReadMenu.setVisibility(GONE);
            mTTSMenu.setVisibility(GONE);
            mTTSMenu.setVisibility(GONE);
        }
        if (mAblTopMenu.getVisibility() == View.VISIBLE) {
            //关闭
            mAblTopMenu.startAnimation(mTopOutAnim);
            mLlBottomMenu.startAnimation(mBottomOutAnim);
            mIvAutoPlay.startAnimation(mLeftOutAnim);
            mIvListen.startAnimation(mLeftOutAnim);
            mAblTopMenu.setVisibility(GONE);
            mLlBottomMenu.setVisibility(GONE);
            mTvPageTip.setVisibility(GONE);
            mIvAutoPlay.setVisibility(GONE);
            mIvListen.setVisibility(GONE);
            mRlAddToCollection.setVisibility(GONE);
            if(!isCollected) {
                mRlAddToCollection.startAnimation(mRightOutAnim);
            }
//            if (hideStatusBar) {
//            hideSystemBar();
//            }
        } else {
            mAblTopMenu.setVisibility(View.VISIBLE);
            mLlBottomMenu.setVisibility(View.VISIBLE);
            mIvAutoPlay.setVisibility(VISIBLE);
            mIvListen.setVisibility(VISIBLE);
            if(!isCollected) {
                mRlAddToCollection.setVisibility(VISIBLE);
                mRlAddToCollection.startAnimation(mRightInAnim);
            }
            mAblTopMenu.startAnimation(mTopInAnim);
            mLlBottomMenu.startAnimation(mBottomInAnim);
            mIvAutoPlay.startAnimation(mLeftInAnim);
            mIvListen.startAnimation(mLeftInAnim);

//            showSystemBar();
//            hideSystemBar();
        }
    }

    //初始化菜单动画
    private void initMenuAnim() {
        if (mTopInAnim != null) return;

        mTopInAnim = AnimationUtils.loadAnimation(this, R.anim.slide_top_in);
        mTopOutAnim = AnimationUtils.loadAnimation(this, R.anim.slide_top_out);
        mBottomInAnim = AnimationUtils.loadAnimation(this, R.anim.slide_bottom_in);
        mBottomOutAnim = AnimationUtils.loadAnimation(this, R.anim.slide_bottom_out);
        mLeftInAnim = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
        mLeftOutAnim = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
        mRightInAnim = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
        mRightOutAnim = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
        //退出的速度要快
        mTopOutAnim.setDuration(200);
        mBottomOutAnim.setDuration(200);
        mLeftOutAnim.setDuration(200);
    }

    @Override
    protected void startLogic() {

        super.startLogic();
        mPageLoader.updateBattery(getBatteryNow());
        // 如果是已经收藏的，那么就从数据库中获取目录
//        List<MediaChapterBean> inputChapterBeanList = mCollectionMediaBean.getMediaChapterList();
        if (inputChapterBeanList != null && inputChapterBeanList.size() > 0) {
            showCatalog(inputChapterBeanList);
        } else {
            if (isCollected) {
                Disposable disposable = MediaStorageManager.getInstance()
                        .getMediaChaptersInRx(mCollectionMediaBean.getId())
                        .compose(RxUtils::toSimpleSingle)
                        .subscribe(
                                (mediaChapterBeanList, throwable) -> {
                                    if (mediaChapterBeanList == null || mediaChapterBeanList.isEmpty()) {
                                        //保存了都没找到;很可能是换源之后强行清除了
                                        if (mCollectionMediaBean.getIfLocal()) {
                                            //如果是本地书籍，可能真的没有章节，随便的txt而已
                                            mPageLoader.refreshChapterList();
                                            return;
                                        }
                                        mPresenter.loadCatalog(mSiteSourceBean, mCollectionMediaBean);
                                        return;
                                    }
                                    showCatalog(mediaChapterBeanList);
                                    // 设置 CollBook
                                    mPageLoader.getShelfBook().setMediaChapterList(mediaChapterBeanList);
                                    // 刷新章节列表
//                                    mPageLoader.refreshChapterList();
                                    // 如果是网络小说并被标记更新的，则从网络下载目录
//                                    if (mCollectionMediaBean.getIfUpdated() && !mCollectionMediaBean.getIfLocal()) {
//                                        mPresenter.loadCatalog(mSiteSourceBean, mCollectionMediaBean);
//                                    }
                                    LogUtils.e(throwable);
                                }
                        );
                addDisposable(disposable);
            } else {
                // 从网络中获取目录
                mPresenter.loadCatalog(mSiteSourceBean, mCollectionMediaBean);
            }
        }
    }

    /***************************view************************************/
    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }

    private int getMatchedChapterIndex(List<MediaChapterBean> mediaChapterBeanList) {

        double similar = 0.0d;
        int similarIndex = 0;

        for (int i = 0; i < mediaChapterBeanList.size(); i++) {
            MediaChapterBean chapterBean = mediaChapterBeanList.get(i);
            String tempChapterTitle = chapterBean.getName().trim();
            if (tempChapterTitle.equals(inputChapterTitle)) {
                return i;
            }
            double tmpSim = SimilarityUtil.sim(inputChapterTitle.replaceAll("[第章话回話🔐]", ""), tempChapterTitle.replaceAll("[第章回话話🔐]", ""));
            //如果相似度接近，那么用索引值更接近的那个
            if (tmpSim > similar || ((tmpSim == similar) && Math.abs(i - inputChapterIndex) < Math.abs(i - similarIndex))) {
                similar = tmpSim;
                similarIndex = i;
            }
        }
        return similarIndex;

    }

    @Override
    public void showCatalog(List<MediaChapterBean> bookChapters) {
        if (isDestroyed() || isFinishing()) {
            return;
        }
        LogUtils.d("showCatalog , bookChapters = " + bookChapters);
        mPageLoader.getShelfBook().setMediaChapterList(bookChapters);
        //认定inputChapterTitle 和 inputChapterIndex 只会有一个起作用，如果title有了，
        //那么index就没有，用title来生成它
        if (inputChapterIndex == -1 && inputChapterTitle != null) {
            inputChapterIndex = getMatchedChapterIndex(bookChapters);
        }
        MediaRecordBean recordBean = MediaStorageManager.getInstance().getMediaRecord(mCollectionMediaBean.getId());
        if (recordBean == null) {
            recordBean = new MediaRecordBean();
            recordBean.setMediaId(mCollectionMediaBean.getId());
        }
        if (inputChapterIndex >= 0) {
            //手动选择跟保存的不一样的章节
            recordBean.setChapter(inputChapterIndex);
            recordBean.setPagePos(inputPage >= 0 ? inputPage : 0);
            MediaStorageManager.getInstance().saveMediaRecord(recordBean);

            //用上面保存的阅读记录，重新初始化书籍
            mPageLoader.prepareBook();
            mPageLoader.refreshChapterListAndJumpToChapter(inputChapterIndex);
        } else {
            mPageLoader.refreshChapterList();
        }

        // 如果是目录更新的情况，那么就需要存储更新数据
        if (mCollectionMediaBean.getIfUpdated() && isCollected) {
            MediaStorageManager.getInstance()
                    .saveMediaChaptersWithAsync(bookChapters);
        }
    }

    @Override
    public void finishChapter() {
        if (isDestroyed() || isFinishing()) {
            return;
        }
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
            mHandler.sendEmptyMessage(WHAT_CHAPTER);
        }
        // 当完成章节的时候，刷新列表
        mBookCatalogAdapter.notifyDataSetChanged();
    }

    @Override
    public void errorChapter() {
        if (isDestroyed() || isFinishing()) {
            return;
        }
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
            mPageLoader.chapterError();
        }
    }

    @Override
    public void onBackPressed() {
        if (mAblTopMenu.getVisibility() == View.VISIBLE) {
            // 非全屏下才收缩，全屏下直接退出
            if (!ReadSettingManager.getInstance().isFullScreen()) {
                toggleMenu(true);
                return;
            }
        } else if (mSettingDialogFragment.getDialog() != null && mSettingDialogFragment.getDialog().isShowing()) {
            mSettingDialogFragment.dismiss();
            return;
        } else if (mDlSlide.isDrawerOpen(GravityCompat.START)) {
            mDlSlide.closeDrawer(GravityCompat.START);
            return;
        }

        mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        if (!mCollectionMediaBean.getIfLocal() && !isCollected
                && !mCollectionMediaBean.getMediaChapterList().isEmpty()) {
            showDialogAndExit();
        } else {
            exit();
        }
    }

    private void showDialogAndExit() {

        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("加入书架")
                .setMessage("喜欢本书就加入书架吧")
                .setPositiveButton("确定", (dialog, which) -> {
                    saveMedia();
                    exit();
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    exit();
                }).create();
        alertDialog.show();
    }

    private void saveMedia() {
        //设置为已收藏
        isCollected = true;
        //设置阅读时间
        mCollectionMediaBean.setLastRead(StringUtils.
                dateConvert(System.currentTimeMillis(), WaConstants.FORMAT_BOOK_DATE));

        MediaStorageManager.getInstance()
                .saveCollectionMediaWithAsync(mCollectionMediaBean);

        if (mPageLoader != null) {
            mPageLoader.saveRecord();
        }

        RxBus.get().post(RxEvent.MEDIA_COLLECTION_ADD, mCollectionMediaBean);

    }

    // 退出
    private void exit() {
        Intent result = new Intent();
        result.putExtra(MediaDetailActivity.RESULT_IS_COLLECTED, isCollected);
        setResult(Activity.RESULT_OK, result);

        RxBus.get().post(RxEvent.MEDIA_COLLECTION_REFRESH, mCollectionMediaBean);
        // 退出
        super.onBackPressed();
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerBrightObserver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_KEEP_SCREEN_ON)) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
//        mWakeLock.acquire();
//        initData();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        mWakeLock.release();
        if (!ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_KEEP_SCREEN_ON)) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
        if (isCollected) {
            mPageLoader.saveRecord();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterBrightObserver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);

        mHandler.removeMessages(WHAT_CATEGORY);
        mHandler.removeMessages(WHAT_CHAPTER);

        mPageLoader.closeBook();
        mPageLoader = null;

        VoiceService.stop(this);
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean isVolumeTurnPage = ReadSettingManager
                .getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_VOLUME_TO_CHANGE_PAGE);
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (!isTTSRunning && isVolumeTurnPage) {
                    return mPageLoader.skipToPrePage();
                }
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (!isTTSRunning && isVolumeTurnPage) {
                    return mPageLoader.skipToNextPage();
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            LogUtils.e("BookReadActivity onActivityResult ,resultCode not ok, is " + resultCode);
            return;
        }
//        SystemBarUtils.hideStableStatusBar(this);
        if (requestCode == REQUEST_MORE_SETTING) {
            boolean fullScreen = ReadSettingManager.getInstance().isFullScreen();
            if (isFullScreen != fullScreen) {
                isFullScreen = fullScreen;
                // 刷新BottomMenu
                initBottomMenu();
            }

            // 设置显示状态
            if (isFullScreen) {
//                SystemBarUtils.hideStableNavBar(this);
            } else {
//                SystemBarUtils.showStableNavBar(this);
            }
        } else if (requestCode == REQUEST_CHANGE_TYPEFACE) {
            String typefaceFilePath = data.getStringExtra("data");
            if (mPageLoader != null) {
                mPageLoader.setTypeface(typefaceFilePath);
            }
        } else if (requestCode == REQUEST_CHANGE_SOURCE) {
            //先删除老的
            hideReadMenu();
            mBookCatalogAdapter.clear();

            inputChapterIndex = mPageLoader.getChapterPos();
            inputChapterTitle = mPageLoader.getChapterTitle();
//            mPageLoader.closeBook();

            MediaStorageManager.getInstance().deleteCollBook(mCollectionMediaBean);
            //再制作新的
            mCollectionMediaBean = data.getParcelableExtra("bean");
            mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
            mSiteSourceBean = mCollectionMediaBean.getSiteSourceBean();
            mPageLoader = mPvPage.newPageLoader(mCollectionMediaBean);
            initPageLoaderEvent();
//            mPageLoader.setCollectionMediaBean(mCollectionMediaBean);
            mCollectionMediaBean.setMediaChapterList(new ArrayList<>());
            MediaStorageManager.getInstance().saveCollectionMedia(mCollectionMediaBean);
            RxBus.get().post(RxEvent.MEDIA_COLLECTION_REFRESH, mCollectionMediaBean);
            inputChapterBeanList = null;
//            mPageLoader.setPageStatus(PageLoader.STATUS_LOADING);
            startLogic();

        } else if (requestCode == REQUEST_CODE_CHOOSE_PICTURE) {
            List<Uri> selected = Matisse.obtainResult(data);
            if (selected != null && selected.size() > 0) {
                LogUtils.e("TWTW", "URI is " + selected.get(0).getPath());
                LogUtils.e("TWTW", "URI is " + selected.get(0));
                if (mSettingDialogFragment == null) {
                    return;
                }
                if (mSettingDialogFragment.getReadSettingCommonFragment() == null) {
                    return;
                }
                if (mSettingDialogFragment.getReadSettingCommonFragment().getNovelBackgroundDialogFragment() == null) {
                    return;
                }
                mSettingDialogFragment.getReadSettingCommonFragment().getNovelBackgroundDialogFragment().onPictureSelected(selected.get(0));
//                Glide.with(this).load(selected.get(0));


            }

        } else if (requestCode == REQUEST_CODE_REPLACE_RULE) {
            if (mPageLoader != null) {
                mPageLoader.reDrawCurPage(true);
                mPageLoader.preLoadNextChapter();
            }
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_reader, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //TODO refresh，delete chapter cache
        int id = item.getItemId();
        if (id == R.id.action_detail) {
            mCollectionMediaBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
            MediaDetailActivity.startActivity(this, mCollectionMediaBean, mCollectionMediaBean.getMediaChapterList());
        } else if (id == R.id.action_view_by_browser) {
            if (mCollectionMediaBean == null || mCollectionMediaBean.getMediaChapterList().isEmpty() || mPageLoader == null) {
                return true;
            }
            SiteSourceBean siteSourceBean = mCollectionMediaBean.getSiteSourceBean();
            String link = mCollectionMediaBean.getMediaChapterList().get(mPageLoader.getChapterPos()).getLink();
            openUrl(URLUtils.getAbsolutePath(siteSourceBean.getSiteHostUrl(), link));
        } else if (id == R.id.action_text_filter) {
            String siteHostUrl = null;
            if (!mCollectionMediaBean.getIfLocal() && mCollectionMediaBean.getSiteSourceBean() != null) {
                siteHostUrl = mCollectionMediaBean.getSiteSourceBean().getSiteHostUrl();
            }
            ReplaceRuleActivity.startThisForResult(this, REQUEST_CODE_REPLACE_RULE, mCollectionMediaBean.getTitle(), siteHostUrl);
        } else if (id == R.id.action_refresh) {
            if (mPageLoader != null) {
                mPageLoader.reDrawCurPage(true);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    public void openUrl(String url) {
        Intent intent = new Intent();
        intent.setData(Uri.parse(url));//Url 就是你要打开的网址
        intent.setAction(Intent.ACTION_VIEW);
        this.startActivity(intent); //启动浏览器
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initImmersionBar();
    }


    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(RxEvent.VOICE_TTS_DONE)})
    public void onTTSDone(String ttsId) {
        if (mPageLoader != null) {
            mPageLoader.onTTSDone();
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(RxEvent.VOICE_TTS_ERROR)})
    public void onTTSError(String ttsId) {
        stopTTS();
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(RxEvent.VOICE_TTS_STOP)})
    public void onTTSStop(String ttsId) {
        stopTTS();

    }


    @Subscribe(thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(RxEvent.MEDIA_COLLECTION_REMOVE)
            })
    public void onCollectionRemoved(CollectionMediaBean collectionMediaBean) {
        if (collectionMediaBean.getId().equals(mCollectionMediaBean.getId())) {
            isCollected = false;
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxEvent.MEDIA_COLLECTION_ADD)
            })
    public void onCollectionAdded(CollectionMediaBean collectionMediaBean) {
        if (collectionMediaBean.getId().equals(mCollectionMediaBean.getId())) {
            isCollected = true;
        }
    }
}
